package com.kafka.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public abstract class HttpUtil{
	public static Logger log = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * 
	 */
//	private static final long serialVersionUID = 6406429834606739126L;
	public static final String DEFAULT_CHARSET = "utf-8";
	private static final String METHOD_POST = "POST";
//	private static final String METHOD_GET = "GET";
	private static int CONNECTTIMEOUT= 60000;
	private static int READTIMEOUT=60000;
	
	private HttpUtil() {
		PropertyConfigurator.configure("log4j.properties");
	}

	
	/**
	 * 执行HTTP POST请求。
	 * 
	 * @param url 请求地址
	 * @param params 请求参数
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doPost(String url, String params,String appID,String secretKey) throws IOException {
		return doPost(url, params, appID, secretKey, DEFAULT_CHARSET);
	}

	/**
	 * 执行HTTP POST请求。
	 * @param url 请求地址
	 * @param ctype 请求类型
	 * @param content 请求字节数组
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doPost(String url, String params,String appID,String secretKey, String charset) throws IOException {
		log.info("#######HttpUtil_print|params:"+params);
		HttpURLConnection conn = null;
		OutputStream out = null;
		String rsp = null;
		
		try {
			String ctype = "application/json;charset=" + charset;
//			String query = buildQuery(params, charset);
			String query = params;
			byte[] content={};
			if(query!=null){
				content=query.getBytes(charset);
			}
			try{
				conn = getConnection(new URL(url), METHOD_POST, ctype, appID, params, secretKey);	
				conn.setConnectTimeout(CONNECTTIMEOUT);
				conn.setReadTimeout(READTIMEOUT);
				
				
			}catch(IOException e){
				throw e;
			}
			try{
				out = conn.getOutputStream();
				out.write(content);
				rsp = getResponseAsString(conn);
			}catch(IOException e){
				throw e;
			}
			
		}finally {
			if (out != null) {
				out.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}

		return rsp;
	}

	private static HttpURLConnection getConnection(URL url, String method, String ctype,String appID,String params,String secretKey)
			throws IOException {
		InetAddress ipaddr = InetAddress.getLocalHost();
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(method);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		//conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
		log.info("#######HttpUtil_print|appID:"+appID+",secretKey:"+secretKey);
		conn.setRequestProperty("User-Agent", "uus-sdk-java");
		conn.setRequestProperty("Content-Type", ctype);
		conn.setRequestProperty("API-RemoteIP", ipaddr.getHostAddress());
		conn.setRequestProperty("AppID", appID);
		Date date = new Date();       
		Timestamp timestamp = new Timestamp(date.getTime());
		conn.setRequestProperty("TS", timestamp.toString());
//		conn.setRequestProperty("TS", "2015-09-02 11:30:59.473");
		log.info("#######HttpUtil_print|timestamp:"+timestamp.toString());
		StringBuffer values = new StringBuffer(); 
		values.append(timestamp);
		values.append(params);
		values.append(secretKey);
//		String values = "2015-09-02 11:30:59.473" + params + secretKey;
		String md5 = MD5Util.toMD5(values.toString().trim());
		log.info("#######HttpUtil_print|values:"+values.toString().trim()+",DM5:"+md5);
		conn.setRequestProperty("Token", md5);
		return conn;
	}

	public static String buildQuery(Map<String, String> params, String charset) throws IOException {
		if (params == null || params.isEmpty()) {
			return null;
		}

		StringBuilder query = new StringBuilder();
		Set<Entry<String, String>> entries = params.entrySet();
		boolean hasParam = false;

		for (Entry<String, String> entry : entries) {
			String name = entry.getKey();
			String value = entry.getValue();
			// 忽略参数名或参数值为空的参数
			if (StringUtil.areNotEmpty(name, value)) {
				if (hasParam) {
					query.append("&");
				} else {
					hasParam = true;
				}

				query.append(name).append("=").append(URLEncoder.encode(value, charset));
			}
		}

		return query.toString();
	}

	protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
		String charset = getResponseCharset(conn.getContentType());
		InputStream es = conn.getErrorStream();
		if (es == null) {
			return getStreamAsString(conn.getInputStream(), charset);
		} else {
			String msg = getStreamAsString(es, charset);
			if (StringUtil.isEmpty(msg)) {
				throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
			} else {
				throw new IOException(msg);
			}
		}
	}

	private static String getStreamAsString(InputStream stream, String charset) throws IOException {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
			StringWriter writer = new StringWriter();

			char[] chars = new char[256];
			int count = 0;
			while ((count = reader.read(chars)) > 0) {
				writer.write(chars, 0, count);
			}

			return writer.toString();
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

	private static String getResponseCharset(String ctype) {
		String charset = DEFAULT_CHARSET;

		if (!StringUtil.isEmpty(ctype)) {
			String[] params = ctype.split(";");
			for (String param : params) {
				param = param.trim();
				if (param.startsWith("charset")) {
					String[] pair = param.split("=", 2);
					if (pair.length == 2) {
						if (!StringUtil.isEmpty(pair[1])) {
							charset = pair[1].trim();
						}
					}
					break;
				}
			}
		}

		return charset;
	}

	/**
	 * 使用默认的UTF-8字符集反编码请求参数值。
	 * 
	 * @param value 参数值
	 * @return 反编码后的参数值
	 */
	public static String decode(String value) {
		return decode(value, DEFAULT_CHARSET);
	}

	/**
	 * 使用默认的UTF-8字符集编码请求参数值。
	 * 
	 * @param value 参数值
	 * @return 编码后的参数值
	 */
	public static String encode(String value) {
		return encode(value, DEFAULT_CHARSET);
	}

	/**
	 * 使用指定的字符集反编码请求参数值。
	 * 
	 * @param value 参数值
	 * @param charset 字符集
	 * @return 反编码后的参数值
	 */
	public static String decode(String value, String charset) {
		String result = null;
		if (!StringUtil.isEmpty(value)) {
			try {
				result = URLDecoder.decode(value, charset);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}

	/**
	 * 使用指定的字符集编码请求参数值。
	 * 
	 * @param value 参数值
	 * @param charset 字符集
	 * @return 编码后的参数值
	 */
	public static String encode(String value, String charset) {
		String result = null;
		if (!StringUtil.isEmpty(value)) {
			try {
				result = URLEncoder.encode(value, charset);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}

	/**
	 * 从URL中提取所有的参数。
	 * 
	 * @param query URL地址
	 * @return 参数映射
	 */
	public static Map<String, String> splitUrlQuery(String query) {
		Map<String, String> result = new HashMap<String, String>();

		String[] pairs = query.split("&");
		if (pairs != null && pairs.length > 0) {
			for (String pair : pairs) {
				String[] param = pair.split("=", 2);
				if (param != null && param.length == 2) {
					result.put(param[0], param[1]);
				}
			}
		}

		return result;
	}

	public static void main(String[] args) throws IOException {
		try {
			JSONObject jsonData = new JSONObject();
			jsonData.put("UUID", "14edb3b3-22d7-4ddd-9a54-786adead7303");
			jsonData.put("LoginName", "new_test01");
			jsonData.put("Phone", "3398757");
			jsonData.put("Healthcare_card", "12345679");
			jsonData.put("Avatar", "双子");
			jsonData.put("Weixin", "honganlei");
			jsonData.put("True_name", "雷洪岸888");
			jsonData.put("Passwd", "a8nwWkwYsCAeJW1ChqKaiQ==");
			jsonData.put("Birthday", "1985-06-04");
			jsonData.put("Agedness_card", "10247442222");
			jsonData.put("QQ", "283729055");
			jsonData.put("Area_info", "青秀区");
			jsonData.put("Mobile", "18911866244");
			jsonData.put("Community", "团员");
			jsonData.put("Contact", "无");
			jsonData.put("Spouse_name", "张某某001");
			jsonData.put("Email", "28371288@163.com");
			jsonData.put("Spouse_status", "活着");
			jsonData.put("Username", "shuangzi");
			jsonData.put("Address", "广西南宁某小区");
			jsonData.put("Sid", "450103198506041016");
			
			jsonData.put("Constellation", 1);
			jsonData.put("User_class", 1);
			jsonData.put("Politics", 1);
			jsonData.put("Area", 2);
			jsonData.put("Zodiac", 1);
			jsonData.put("Nation", 3);
			jsonData.put("Integral", 2);
			jsonData.put("Service_class", 1);
			jsonData.put("Marriage", 0);
			jsonData.put("Province", 1);
			jsonData.put("Nationality", 3);
			jsonData.put("City", 2);
			jsonData.put("Source", 1);
			jsonData.put("District", 1);
			jsonData.put("Gender", 0);
			
//			jsonData.put("Uuid", "14edb3b3-22d7-4ddd-9a54-786adead7303");
//			jsonData.put("cardno", "TS0010");
//			jsonData.put("cardtype", 1);
//			jsonData.put("amount", 100);
//			jsonData.put("goodsname", "保健药");
//			jsonData.put("goodstype", "6");
//			jsonData.put("shopcode", "1000001");
//			jsonData.put("paydevice", "IC");
//			jsonData.put("paydate", "2015-06-08");
//			jsonData.put("payno", "201508240019");
			
			String rs = HttpUtil.doPost("http://120.24.53.64:7928/api/user/doc/sets", jsonData.toString(),"T002","def1010FTZ");
//			String rs = HttpUtil.doPost("http://10.8.0.10:8080/dc/pay/pay", jsonData.toString(),"T002","def1010FTZ");
			System.out.println(rs);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.toString());
		}
//		String s = "2015-09-02 11:30:59.473{\"User_class\":1,\"Uuid\":\"52fa2e73-9604-4c35-9edf-000000\",\"Phone\":\"0771-3398757\",\"Politics\":1,\"LoginName\":\"test01\",\"Healthcare_card\":\"12345679\",\"Area\":2,\"Avatar\":\"双子\",\"Weixin\":\"honganlei\",\"True_name\":\"雷洪岸\",\"Passwd\":\"a8nwWkwYsCAeJW1ChqKaiQ==\",\"Constellation\":1,\"Agedness_card\":\"5666666255\",\"Birthday\":\"1985-06-04\",\"Zodiac\":1,\"Nation\":3,\"Area_info\":\"青秀区\",\"Mobile\":\"18978950001\",\"Community\":\"团员\",\"Service_class\":1,\"Integral\":2,\"Contact\":\"无\",\"Marriage\":0,\"Province\":1,\"Nationality\":3,\"City\":2,\"Spouse_name\":\"张某某\",\"Qq\":\"283729055\",\"Source\":1,\"Email\":\"283729845@qq.com\",\"District\":8,\"Spouse_status\":\"活着\",\"Address\":\"广西南宁某小区\",\"Username\":\"shuangzi\",\"Gender\":0,\"Sid\":\"450103198506041016\"}skdemosk";
//		System.out.println(MD5Util.toMD5(s));
	}
}
